package net.oschina.app.base;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

import net.oschina.app.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shinelon on 2017/1/13.
 */

public class BasePagerAdapter extends FragmentStatePagerAdapter {
    private List<Class<? extends BaseFragment>> pagers = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private Context mContext;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;

    public BasePagerAdapter(FragmentManager fm, BaseActivity activity) {
        super(fm);
        mViewPager = (ViewPager) activity.findViewById(R.id.vp);
        mTabLayout = (TabLayout) activity.findViewById(R.id.tb);
        mContext = mViewPager.getContext();
        mViewPager.setAdapter(this);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    public BasePagerAdapter(FragmentManager fm, View rootView) {
            super(fm);
            mViewPager = (ViewPager) rootView.findViewById(R.id.vp);
            mTabLayout = (TabLayout) rootView.findViewById(R.id.tb);
            mContext = mViewPager.getContext();
            mViewPager.setAdapter(this);
            mTabLayout.setupWithViewPager(mViewPager);
    }

    @Override
    public Fragment getItem(int position) {
        return Fragment.instantiate(mContext,pagers.get(position).getName());
    }

    @Override
    public int getCount() {
        return pagers==null?0:pagers.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (titles.size()<=0){
            return null;
        }
        return titles.get(position);
    }

    public void addTab(Class<? extends BaseFragment> clz,String title) {
        pagers.add(clz);
        titles.add(title);
        notifyDataSetChanged();
    }

    public void isFixTabLayout(boolean flag) {
        if (mTabLayout!=null){
            if (flag) {
                mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            }else {
                mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            }
        }
    }
}
